package com.asura.app.wechat.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.util.AttributeSet;

import com.asura.app.library.imageload.ImageLoadOptions;
import com.asura.app.library.imageload.ImageLoader;
import com.asura.app.wechat.R;
import com.asura.app.wechat.common.WechatModuleProvider;

/**
 * Created by Asura on 2017/12/29.
 */

public class NetworkImageView extends android.support.v7.widget.AppCompatImageView {

    private final int placeholderResId;
    private final int errorResId;
    private final String url;
    private ImageLoader imageLoader;

    public NetworkImageView(Context context) {
        this(context, null);
    }

    public NetworkImageView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public NetworkImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.NetworkImageView, defStyleAttr, R.style.DefaultNetworkImageView);
        placeholderResId = typedArray.getResourceId(R.styleable.NetworkImageView_placeholderResId, 0);
        errorResId = typedArray.getResourceId(R.styleable.NetworkImageView_errorResId, 0);
        url = typedArray.getString(R.styleable.NetworkImageView_url);
        typedArray.recycle();
        imageLoader = WechatModuleProvider.getInstance().getImageLoader();
        if (url != null) {
            load(url);
        }
    }


    public void load(String url) {
        ImageLoadOptions.Builder builder = new ImageLoadOptions.Builder();
        if (placeholderResId != 0) {
            builder.placeHolder(getResources().getDrawable(placeholderResId));
        }
        if (errorResId != 0) {
            builder.error(getResources().getDrawable(errorResId));
        }
        builder
                .width(ImageLoadOptions.UNKNOW)
                .height(ImageLoadOptions.UNKNOW)
                .url(url);
        imageLoader.load(getContext(), this, builder.build(), null);
    }
}
